const path = require('path')
const webpack = require('webpack')
const TerserPlugin = require('terser-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const { getArgs } = require('@lhy-assist/node')
const { cipher } = require('@lhy-assist/utils')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const { name } = require('./package.json')

const env = getArgs('env') || 'production'
const analyze = getArgs('analyze') === 'true'
const config = require('./config/index')({}, env)
const isDev = ['development', 'dev'].includes(env)

const plugins = []
if (analyze) {
  plugins.push(new BundleAnalyzerPlugin())
}

module.exports = {
  mode: isDev ? 'development' : 'production',
  entry: {
    index: './src/main.tsx',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
            },
          },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.(ttf|eot|svg|woff2?)(\?[\s\S]+)?$/,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[hash][ext][query]',
        },
      },
      {
        test: /\.(png|jpe?g|gif|svg?)$/,
        type: 'asset',
        parser: { dataUrlCondition: { maxSize: 10 * 1024 } },
        generator: { filename: 'img/[hash][ext][query]' },
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /[^module]\.s[ac]ss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              additionalData: `
                  @use "@/asset/css/common/_var.scss"as *;
                `,
            },
          },
        ],
      },
      {
        test: /\.module.s[ac]ss$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              modules: {
                localIdentName: '[local]_[hash:base64:5]',
              },
            },
          },
          {
            loader: 'sass-loader',
            options: {
              additionalData: `
                  @use "@/asset/css/common/_var.scss"as *;
                `,
            },
          },
        ],
      },
    ],
  },
  plugins: [
    ...plugins,
    new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
    new ForkTsCheckerWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './index.html',
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[chunkhash].css',
    }),
    new webpack.DefinePlugin({
      'process.config': cipher.encodeEnv(config),
    }),
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          name: 'vendor',
          test: /node_modules/,
          chunks: 'all',
          reuseExistingChunk: true,
          maxSize: 6 * 1024 * 1024,
          priority: 0,
        },
      },
    },
    minimizer: [
      new CssMinimizerPlugin({
        parallel: true,
      }),
      new TerserPlugin({
        parallel: true,
        extractComments: false,
        terserOptions: {
          format: {
            comments: false,
          },
        },
      }),
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js', '.html'],
    conditionNames: ['require', 'node'],
    alias: {
      '@': path.join(__dirname, 'src'),
    },
  },
  devtool: isDev ? 'inline-source-map' : false,
  output: {
    publicPath: config.BASE_URL || '/',
    filename: 'js/[name].[chunkhash].js',
    path: path.resolve(__dirname, 'dist'),
    library: `${name}-[name]`,
    libraryTarget: 'umd',
    globalObject: 'window',
  },
  devServer: {
    historyApiFallback: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
}
